import * as $dataform from '@/management/api/dataform'
import * as $collect from '@/management/api/dataform-collect'
import { CODE_MAP } from '@/management/api/eco/base'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
// import { getSurveyList as surveyList } from '@/management/api/survey'
import { set } from 'lodash-es'
import { arrayToTree } from '@/management/utils/index'
import { OptionType, FormType, optionMenus } from '@/management/utils/types/formsTypes'

export default {
  namespaced: true,
  state: {
    // 分类管理
    optionType: OptionType.Personal,
    optionMenus: optionMenus,
   
    formType: FormType.Forms,
    formsList: [], // 活动列表
    formsTotal: 0,
    formsHasMore: true,
    formDetail: null,
    directoryList: [],
    
    workspaceId: '-1',
    spaceDetail: null,
    teamSpaceList: [],
    // 列表管理
    surveyList: [],
    surveyTotal: 0,
    searchVal: '',
    selectValueMap: {
      busineType: '',
      'status': ''
    },
    buttonValueMap: {
      lastModifyTime: '',
      // createTime: -1
    }
  },
  getters: {
    listFliter(state) {
      return [
        {
          comparator: '',
          condition: [
            {
              field: 'formName',
              value: state.searchVal,
              comparator: '$regex'
            }
          ]
        },
        {
          comparator: '',
          condition: [
            {
              field: 'status',
              value: state.selectValueMap['status']
            }
          ]
        }
        // {
        //   comparator: '',
        //   condition: [
        //     {
        //       field: 'busineType',
        //       value: state.selectValueMap.busineType
        //     }
        //   ]
        // }
      ]
    },
    listOrder(state) {
      const { buttonValueMap } = state
      return Object.entries(buttonValueMap)
        .filter(([, effectValue]) => effectValue)
        .reduce((prev, item) => {
          const [effectKey, effectValue] = item
          prev.push({ field: effectKey, value: effectValue })
          return prev
        }, [])
    }
  },
  mutations: {
    changeFormType(state, formType) {
      state.formType = formType
    },
    changeOptionType(state, optionType) {
      // 切换操作类型清除筛选条件
      this.commit('dataform/reserSelectValueMap')
      this.commit('dataform/reserButtonValueMap')
      this.commit('dataform/setSearchVal', '')
      state.optionType = optionType
    },
    setFormDetail(state, data) {
      state.formDetail = data
    },
    setFormsList(state, list) {
      state.formsList = list
    },

    setDirectoryList(state, list) {
      state.directoryList = list
    },
    setFormsTotal(state, total) {
      state.formsTotal = total
    },

    setFormsHasMore(state, hasMore) {
      state.formsHasMore = hasMore
    },

    setSearchVal(state, data) {
      state.searchVal = data
    },
    reserSelectValueMap(state) {
      state.selectValueMap = {
        busineType: '',
        status: ''
      }
    },
    changeSelectValueMap(state, { key, value }) {
      state.selectValueMap[key] = value
    },
    reserButtonValueMap(state) {
      state.buttonValueMap = {
        lastModifyTime: '',
        // createTime: -1
      }
    },
    changeButtonValueMap(state, { key, value }) {
      state.buttonValueMap[key] = value
    },

    changeWorkSpace(state, workSpaceId) {
      // 切换空间清除筛选条件
      this.commit('dataform/reserSelectValueMap')
      this.commit('dataform/reserButtonValueMap')
      this.commit('dataform/setSearchVal', '')
      state.workSpaceId = workSpaceId
    },
    setSpaceDetail(state, data) {
      state.spaceDetail = data
    },
    updateSpaceMenus(state, teamSpace) {
      // 更新空间列表下的团队空间
      set(state, 'optionMenus[1].children', teamSpace)
    },
  },
  actions: {
    async getDirectoryList({ commit }, payload) {
      try {
        let params = {
          pageNo: payload?.curPage || 1,
          pageSize: 999, // 默认一页10条
          condition: {
            parentId: '-1',
            optionType: OptionType.Personal,
            formType: FormType.Dirs,
          }
        }
        const res = await $dataform.tree(params)
        if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
          const list = res?.result || []
          const teamSpace = list.map((item) => {
            return {
              id: item.formId + '_' + OptionType.Personal,
              parentId: item.parentId + '_' + OptionType.Personal,
              formId: item.formId,
              name: item.formName
            }
          })
          let treelist = arrayToTree(teamSpace)
          let newList = treelist.filter((item) => {
            return item.parentId === '-1_' + OptionType.Personal
          })

          commit('setDirectoryList', newList)
          commit('updateSpaceMenus', newList)
        } else {
          ElMessage.error(res?.serverResult?.resultMessage)
        }
      } catch (err) {
        console.log(err)
      }
    },
    async addDirectory({dispatch}, params) {
      const res = await $dataform.saveDirectory({
        formName: params.formName,
        formRemark: params.formRemark,
        formType: params.formType,
        parentId: params.parentId || '-1'
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('更新成功')
        dispatch('getDirectoryList')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async updateDirectory({state}, params) {
      const res = await $dataform.updateDirectory({
        formId: params._id,
        formName: params.formName,
        formRemark: params.formRemark,
        formType: params.formType,
        parentId: params.parentId || state.workSpaceId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('更新成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async deleteDirectory({}, optionType) {
      try {
        const res = await $dataform.delDirectory(optionType)

        if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
          ElMessage.success('删除成功')
        } else {
          ElMessage.error(res.serverResult.resultMessage)
        }
      } catch (err) {
        ElMessage.error(err)
      }
    },
    async getDirectoryDetail({ state, commit }, id) {
      try {
        const workspaceId = id || state.workSpaceId
        const res = await $dataform.get(workspaceId)
        if (res?.serverResult?.resultCode === CODE_MAP.SUCCESS) {
          commit('setSpaceDetail', res.data)
        } else {
          ElMessage.error('getSpaceList' + res?.serverResult?.resultMessage)
        }
      } catch (err) {
        ElMessage.error('getSpaceList' + err)
      }
    },
    async addCollect({}, params) {
      const res = await $collect.save({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async delCollect({}, params) {
      const res = await $collect.del({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('添加成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async deleteForm({}, params) {
      const res = await $dataform.del({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async copyForm({}, params) {
      const res = await $dataform.del({
        formId: params.formId
      })

      if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
        ElMessage.success('复制成功')
      } else {
        ElMessage.error(res.serverResult.resultMessage)
      }
    },
    async getFormDetail({ state, commit }, id) {
      try {
        const optionType = id || state.optionType
        const res = await $dataform.get(optionType)
        if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
          commit('setFormDetail', res.data)
        } else {
          ElMessage.error(res.serverResult.resultMessage)
        }
      } catch (err) {
        ElMessage.error('getSpaceList' + err)
      }
    },
    async getFormsList({ state, getters, commit }, payload) {
      if (!state.formsHasMore) {
        return
      }
      let condition = {
        optionType: state.optionType,
        formType: FormType.Forms
      }
      if (state.optionType === OptionType.Personal) {
        condition.parentId = state.workSpaceId || '-1'
        condition.formType = FormType.Dirs
      }
      
      getters.listFliter.filter((item) => {
        return item.condition[0].value
      }).forEach((item) => {
        condition[item.condition[0].field] = item.condition[0].value
      })
      if (state.optionType === OptionType.Recycle) {
        condition.status = '0'
        condition.optionType = OptionType.All
      }
      
      const orderStringTmp = getters.listOrder.map((item) => {
        return item.field + ' ' + (item.value == 1 ? 'asc' : 'desc')
      })
      let orderString = []
      if (state.optionType === OptionType.Personal) {
        orderString = ['formType asc']
      }
      if (orderStringTmp.length > 0) {
        orderString = orderString.concat(orderStringTmp)
      } else {
        orderString = orderString.concat(['lastModifyTime desc'])
      }
      try {
        let params = {
          pageNo: payload?.curPage || 1,
          pageSize: payload?.pageSize || 24, // 默认一页10条
          // filter: filterString,
          orderList: orderString,
          condition: condition
        }

        const res = await $dataform.list(params)
        if (res.serverResult.resultCode === CODE_MAP.SUCCESS) {
          let list = (res?.result?.list || []).map((item) => {
            return {
              _id: item.formId,
              ...item
            }
          }) || []

          if (list.length < 10) {
            commit('setFormsHasMore', false)
          } else {
            commit('setFormsHasMore', true)
          }

          let currenPage = res?.result?.currentPageNo || 0
          let formList = state.formsList.map((item) => {
            return {
              ...item,
            }
          }) || []
          if (params.pageNo === 1) {
            formList = list.map(item => {
              return {
                ...item,
              }
            })
            commit('setFormsList', formList)
          } else {
            // formList = formList.concat([...list])
            list.forEach((item) => {
              formList.push({
                ...item,
              })
            })
            commit('setFormsList', formList)
          }

          commit('setFormsList', formList)
          commit('setFormsTotal', currenPage)
        } else {
          commit('setFormsHasMore', false)
          ElMessage.error(res.serverResult.resultMessage)
        }
      } catch (error) {
        commit('setFormsHasMore', false)
        console.log(error)
      }
    }
  }
}
